document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    if (sessionStorage.getItem('isLoggedIn') !== 'true') {
        window.location.href = 'login.html';
        return;
    }

    // 显示欢迎信息
    const username = sessionStorage.getItem('username');
    if (username) {
        const welcomeUsername = document.getElementById('welcomeUsername');
        if (welcomeUsername) {
            welcomeUsername.textContent = username;
        }
    }

    // 侧边栏切换
    const sidebarCollapse = document.getElementById('sidebarCollapse');
    const sidebar = document.getElementById('sidebar');
    
    sidebarCollapse.addEventListener('click', function() {
        sidebar.classList.toggle('active');
        // 添加内容区域的响应式调整
        document.getElementById('content').classList.toggle('active');
    });

    // 页面切换
    const navLinks = document.querySelectorAll('#sidebar a[data-section]');
    const sections = document.querySelectorAll('.content-section');
    
    function switchToSection(sectionId) {
        // 移除所有active类
        navLinks.forEach(l => l.parentElement.classList.remove('active'));
        sections.forEach(s => s.classList.remove('active'));
        
        // 添加active类到目标section
        const targetSection = document.getElementById(sectionId);
        const targetLink = document.querySelector(`#sidebar a[data-section="${sectionId}"]`);
        
        if (targetSection) {
            targetSection.classList.add('active');
        }
        if (targetLink) {
            targetLink.parentElement.classList.add('active');
        }
    }

    // 侧边栏导航点击事件
    navLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            switchToSection(this.dataset.section);
        });
    });

    // 欢迎页面的快捷操作按钮点击事件
    document.querySelectorAll('.quick-actions a').forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const targetSection = this.getAttribute('href').substring(1); // 移除#号
            switchToSection(targetSection);
        });
    });

    // 进入管理按钮点击事件
    document.querySelectorAll('.action-card .btn').forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            const targetSection = this.getAttribute('href').substring(1); // 移除#号
            switchToSection(targetSection);
        });
    });

    // 退出登录
    const logoutBtn = document.getElementById('logoutBtn');
    logoutBtn.addEventListener('click', function() {
        if (confirm('确定要退出登录吗？')) {
            window.location.href = 'login.html';
        }
    });

    // 课程管理
    const addCourseBtn = document.getElementById('addCourseBtn');
    const courseModal = new bootstrap.Modal(document.getElementById('courseModal'));
    const saveCourseBtn = document.getElementById('saveCourseBtn');
    const courseForm = document.getElementById('courseForm');
    const courseList = document.querySelector('.course-list');

    // 分页相关变量
    let currentPage = 1;
    const pageSize = 10;
    let hasNextPage = true; // 是否有下一页
    
    // 模拟课程数据
    let courses = [
        {
            id: 1,
            name: 'Docker基础实践',
            duration: 2,
            difficulty: '初级',
            description: '学习Docker的基本概念和操作',
            guideFile: 'docker-guide.pdf',
            imageFile: 'docker-image.tar'
        },
        {
            id: 2,
            name: 'Kubernetes集群部署',
            duration: 4,
            difficulty: '中级',
            description: '学习Kubernetes集群的部署和管理',
            guideFile: 'k8s-guide.pdf',
            imageFile: 'k8s-image.tar'
        }
    ];

    // 存储上传后的文件路径
    let uploadedGuideFile = '';
    let uploadedImageFile = '';

    // 处理文件上传
    function handleFileUpload(file, type) {
        const formData = new FormData();
        formData.append('file', file);

        return fetch('http://localhost:8080/common/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                // 保存文件URL
                if (type === 'guide') {
                    uploadedGuideFile = data.data; // 保存文件URL
                } else if (type === 'image') {
                    uploadedImageFile = data.data; // 保存文件URL
                }
                return true;
            } else {
                throw new Error(data.message || '文件上传失败');
            }
        });
    }

    // 监听实验指导书文件选择
    document.getElementById('courseGuide').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            handleFileUpload(file, 'guide')
                .then(() => {
                    alert('实验指导书上传成功！');
                })
                .catch(error => {
                    console.error('上传错误:', error);
                    alert('实验指导书上传失败：' + error.message);
                    this.value = ''; // 清空文件选择
                });
        }
    });

    // 监听镜像文件选择
    document.getElementById('courseImage').addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            handleFileUpload(file, 'image')
                .then(() => {
                    alert('镜像文件上传成功！');
                })
                .catch(error => {
                    console.error('上传错误:', error);
                    alert('镜像文件上传失败：' + error.message);
                    this.value = ''; // 清空文件选择
                });
        }
    });

    // 渲染课程列表
    function renderCourses() {
        courseList.innerHTML = '';
        if (courses.length === 0) {
            courseList.innerHTML = `
                <div class="no-data">
                    <p>暂无课程数据</p>
                </div>
            `;
            // 如果当前页没有数据且不是第一页，自动跳转到上一页
            if (currentPage > 1) {
                currentPage--;
                loadCourses();
                return;
            }
        }

        courses.forEach(course => {
            const courseCard = document.createElement('div');
            courseCard.className = 'course-card';
            courseCard.innerHTML = `
                <h3>${course.name || '未命名课程'}</h3>
                <div class="course-info">
                    <span><i class="fas fa-clock"></i>时长：${course.duration || 0}小时</span>
                    <span><i class="fas fa-signal"></i>难度：${course.level || '未设置'}</span>
                    <span>
                        <i class="fas fa-info-circle"></i>
                        <div class="description-container">
                            <div class="description-label">描述：</div>
                            <div class="description-text">${course.description || '暂无描述'}</div>
                            <div class="description-tooltip">${course.description || '暂无描述'}</div>
                        </div>
                    </span>
                    <span class="file-status ${course.guidePath ? 'status-uploaded' : 'status-not-uploaded'}">
                        <i class="fas fa-file-pdf"></i>
                        <div class="file-info">
                            指导书：${course.guidePath ? 
                                `<a href="${course.guidePath}" target="_blank" class="file-link">查看文件</a>` : 
                                '未上传'}
                        </div>
                    </span>
                    <span class="file-status ${course.imagePath ? 'status-uploaded' : 'status-not-uploaded'}">
                        <i class="fas fa-docker"></i>
                        <div class="file-info">
                            镜像：${course.imagePath ? 
                                `<span class="file-name" title="${course.imagePath}">已上传</span>` : 
                                '未上传'}
                        </div>
                    </span>
                </div>
                <div class="course-actions">
                    <button class="btn btn-primary edit-course" data-id="${course.courseId}">
                        <i class="fas fa-edit"></i> 编辑
                    </button>
                    <button class="btn btn-danger delete-course" data-id="${course.courseId}">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                </div>
            `;
            courseList.appendChild(courseCard);
        });

        // 添加分页控件
        const paginationDiv = document.createElement('div');
        paginationDiv.className = 'pagination-container';
        paginationDiv.innerHTML = `
            <div class="pagination">
                <button class="btn btn-secondary" ${currentPage === 1 ? 'disabled' : ''} onclick="changePage(${currentPage - 1})">
                    <i class="fas fa-chevron-left"></i> 上一页
                </button>
                <span class="page-info">第 ${currentPage} 页</span>
                <button class="btn btn-secondary" ${!hasNextPage ? 'disabled' : ''} onclick="changePage(${currentPage + 1})">
                    下一页 <i class="fas fa-chevron-right"></i>
                </button>
            </div>
        `;
        courseList.appendChild(paginationDiv);

        // 添加编辑和删除事件监听
        document.querySelectorAll('.edit-course').forEach(btn => {
            btn.addEventListener('click', function() {
                const courseId = parseInt(this.dataset.id);
                const course = courses.find(c => c.courseId === courseId);
                if (course) {
                    document.getElementById('courseName').value = course.name || '';
                    document.getElementById('courseDuration').value = course.duration || '';
                    document.getElementById('courseDifficulty').value = course.level || '初级';
                    document.getElementById('courseDescription').value = course.description || '';
                    
                    // 保存已上传的文件路径
                    uploadedGuideFile = course.guidePath || '';
                    uploadedImageFile = course.imagePath || '';

                    // 更新文件上传区域显示
                    updateFileUploadStatus('courseGuide', course.guidePath);
                    updateFileUploadStatus('courseImage', course.imagePath);

                    saveCourseBtn.dataset.id = courseId;
                    courseModal.show();
                }
            });
        });

        document.querySelectorAll('.delete-course').forEach(btn => {
            btn.addEventListener('click', function() {
                const courseId = parseInt(this.dataset.id);
                if (confirm('确定要删除这个课程吗？')) {
                    deleteCourse(courseId);
                }
            });
        });
    }

    // 切换页面
    window.changePage = function(page) {
        if (page < 1) return;
        if (page > currentPage && !hasNextPage) return;
        currentPage = page;
        loadCourses();
    }

    // 加载课程列表
    function loadCourses() {
        fetch(`http://localhost:8080/course/list?page=${currentPage}&pageSize=${pageSize}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    courses = data.data || [];
                    // 如果返回的数据少于pageSize，说明没有下一页了
                    hasNextPage = courses.length === pageSize;
                    renderCourses();
                } else {
                    throw new Error(data.message || '获取课程列表失败');
                }
            })
            .catch(error => {
                console.error('加载课程错误:', error);
                alert('加载课程列表失败：' + error.message);
            });
    }

    // 删除课程
    function deleteCourse(courseId) {
        // 创建 FormData 对象
        const formData = new FormData();
        formData.append('courseId', courseId);

        fetch('http://localhost:8080/course/delete', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('课程删除成功！');
                loadCourses(); // 重新加载当前页
            } else {
                throw new Error(data.message || '删除失败');
            }
        })
        .catch(error => {
            console.error('删除错误:', error);
            alert('删除失败：' + error.message);
        });
    }

    // 添加课程
    addCourseBtn.addEventListener('click', function() {
        courseForm.reset();
        saveCourseBtn.dataset.id = '';
        uploadedGuideFile = '';
        uploadedImageFile = '';
        courseModal.show();
    });

    // 保存课程
    saveCourseBtn.addEventListener('click', function() {
        const courseId = this.dataset.id;
        const teacherId = sessionStorage.getItem('teacherId');

        const courseData = {
            teacherId: parseInt(teacherId),
            name: document.getElementById('courseName').value,
            duration: parseInt(document.getElementById('courseDuration').value),
            level: document.getElementById('courseDifficulty').value,
            description: document.getElementById('courseDescription').value,
            guidePath: uploadedGuideFile,
            imagePath: uploadedImageFile
        };

        // 根据是否有courseId判断是新增还是修改
        const url = courseId ? 
            'http://localhost:8080/course/update' : 
            'http://localhost:8080/course/add';

        if (courseId) {
            courseData.courseId = parseInt(courseId);
        }

        // 发送请求到后端
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(courseData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert(courseId ? '课程修改成功！' : '课程添加成功！');
                courseModal.hide();
                loadCourses();
                // 重置文件上传状态
                uploadedGuideFile = '';
                uploadedImageFile = '';
            } else {
                throw new Error(data.message || '保存失败');
            }
        })
        .catch(error => {
            console.error('保存错误:', error);
            alert('保存失败：' + error.message);
        });
    });

    // 更新文件上传状态显示
    function updateFileUploadStatus(elementId, filePath) {
        const fileInput = document.getElementById(elementId);
        const fileLabel = fileInput.parentElement.querySelector('.file-status');
        if (fileLabel) {
            if (filePath) {
                if (elementId === 'courseGuide') {
                    fileLabel.innerHTML = `
                        <div class="current-file">
                            当前文件：<a href="${filePath}" target="_blank" class="file-link">查看文件</a>
                            <button type="button" class="btn btn-sm btn-outline-danger remove-file" data-type="guide">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div class="upload-new">点击或拖拽上传新文件（可选）</div>
                    `;
                } else {
                    fileLabel.innerHTML = `
                        <div class="current-file">
                            当前文件：<span class="file-name" title="${filePath}">已上传</span>
                            <button type="button" class="btn btn-sm btn-outline-danger remove-file" data-type="image">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div class="upload-new">点击或拖拽上传新文件（可选）</div>
                    `;
                }

                // 添加移除文件的事件监听
                const removeBtn = fileLabel.querySelector('.remove-file');
                if (removeBtn) {
                    removeBtn.addEventListener('click', function(e) {
                        e.preventDefault();
                        const type = this.dataset.type;
                        if (type === 'guide') {
                            uploadedGuideFile = '';
                        } else {
                            uploadedImageFile = '';
                        }
                        updateFileUploadStatus(elementId, '');
                    });
                }
            } else {
                fileLabel.innerHTML = '点击或拖拽上传文件';
            }
        }
    }

    // 用户管理相关变量
    const addUserBtn = document.getElementById('addUserBtn');
    const userModal = new bootstrap.Modal(document.getElementById('userModal'));
    const saveUserBtn = document.getElementById('saveUserBtn');
    const userForm = document.getElementById('userForm');
    const userList = document.querySelector('.user-list');
    let users = [];
    let userCurrentPage = 1;
    const userPageSize = 10;
    let userHasNextPage = true;
    let currentEditingUser = null; // 存储当前正在编辑的用户信息

    // 加载用户列表
    function loadUsers() {
        fetch(`http://localhost:8080/student/list?page=${userCurrentPage}&pageSize=${userPageSize}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    users = data.data || [];
                    userHasNextPage = users.length === userPageSize;
                    renderUsers();
                } else {
                    throw new Error(data.message || '获取用户列表失败');
                }
            })
            .catch(error => {
                console.error('加载用户错误:', error);
                alert('加载用户列表失败：' + error.message);
            });
    }

    // 渲染用户列表
    function renderUsers() {
        userList.innerHTML = '';
        if (users.length === 0) {
            userList.innerHTML = `
                <div class="no-data">
                    <p>暂无用户数据</p>
                </div>
            `;
            // 如果当前页没有数据且不是第一页，自动跳转到上一页
            if (userCurrentPage > 1) {
                userCurrentPage--;
                loadUsers();
                return;
            }
        }

        const table = document.createElement('table');
        table.className = 'user-table';
        table.innerHTML = `
            <thead>
                <tr>
                    <th>用户名</th>
                    <th>邮箱</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                ${users.map(user => `
                    <tr>
                        <td>${user.username || ''}</td>
                        <td>${user.email || ''}</td>
                        <td>
                            <button class="btn btn-primary edit-user" data-id="${user.studentId}">
                                <i class="fas fa-edit"></i> 编辑
                            </button>
                            <button class="btn btn-danger delete-user" data-id="${user.studentId}">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </td>
                    </tr>
                `).join('')}
            </tbody>
        `;
        userList.appendChild(table);

        // 添加分页控件
        const paginationDiv = document.createElement('div');
        paginationDiv.className = 'pagination-container';
        paginationDiv.innerHTML = `
            <div class="pagination">
                <button class="btn btn-secondary" ${userCurrentPage === 1 ? 'disabled' : ''} onclick="changeUserPage(${userCurrentPage - 1})">
                    <i class="fas fa-chevron-left"></i> 上一页
                </button>
                <span class="page-info">第 ${userCurrentPage} 页</span>
                <button class="btn btn-secondary" ${!userHasNextPage ? 'disabled' : ''} onclick="changeUserPage(${userCurrentPage + 1})">
                    下一页 <i class="fas fa-chevron-right"></i>
                </button>
            </div>
        `;
        userList.appendChild(paginationDiv);

        // 添加编辑和删除事件监听
        document.querySelectorAll('.edit-user').forEach(btn => {
            btn.addEventListener('click', function() {
                const studentId = parseInt(this.dataset.id);
                fetch(`http://localhost:8080/student/${studentId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.code === 200) {
                            const user = data.data;
                            currentEditingUser = user; // 保存当前编辑的用户信息
                            document.getElementById('userUsername').value = user.username || '';
                            document.getElementById('userEmail').value = user.email || '';
                            document.getElementById('userPassword').value = ''; // 密码字段置空
                            saveUserBtn.dataset.id = studentId;
                            userModal.show();
                        } else {
                            throw new Error(data.message || '获取用户信息失败');
                        }
                    })
                    .catch(error => {
                        console.error('获取用户信息错误:', error);
                        alert('获取用户信息失败：' + error.message);
                    });
            });
        });

        document.querySelectorAll('.delete-user').forEach(btn => {
            btn.addEventListener('click', function() {
                const studentId = parseInt(this.dataset.id);
                if (confirm('确定要删除这个用户吗？')) {
                    deleteUser(studentId);
                }
            });
        });
    }

    // 删除用户
    function deleteUser(studentId) {
        const formData = new FormData();
        formData.append('studentId', studentId);

        fetch('http://localhost:8080/student/delete', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('用户删除成功！');
                loadUsers(); // 重新加载用户列表
            } else {
                throw new Error(data.message || '删除失败');
            }
        })
        .catch(error => {
            console.error('删除错误:', error);
            alert('删除失败：' + error.message);
        });
    }

    // 添加用户按钮点击事件
    addUserBtn.addEventListener('click', function() {
        currentEditingUser = null; // 清空当前编辑的用户信息
        userForm.reset();
        saveUserBtn.dataset.id = '';
        userModal.show();
    });

    // 保存用户
    saveUserBtn.addEventListener('click', function() {
        const studentId = this.dataset.id;
        const password = document.getElementById('userPassword').value;
        
        // 构建用户数据
        const userData = {
            username: document.getElementById('userUsername').value,
            email: document.getElementById('userEmail').value,
            // 如果是编辑用户且密码为空，使用原密码
            password: password || (currentEditingUser ? currentEditingUser.password : '')
        };

        // 新增用户时密码为必填
        if (!studentId && !password) {
            alert('新增用户时密码不能为空！');
            return;
        }

        // 编辑时添加学生ID
        if (studentId) {
            userData.studentId = parseInt(studentId);
        }

        // 根据是否有studentId判断是新增还是修改
        const url = studentId ? 
            'http://localhost:8080/student/update' : 
            'http://localhost:8080/student/add';

        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(userData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert(studentId ? '用户修改成功！' : '用户添加成功！');
                userModal.hide();
                loadUsers();
            } else {
                throw new Error(data.message || '保存失败');
            }
        })
        .catch(error => {
            console.error('保存错误:', error);
            alert('保存失败：' + error.message);
        });
    });

    // 用户分页切换
    window.changeUserPage = function(page) {
        if (page < 1) return;
        if (page > userCurrentPage && !userHasNextPage) return;
        userCurrentPage = page;
        loadUsers();
    }

    // 初始化用户列表
    loadUsers();

    // 修改密码
    const changePasswordBtn = document.getElementById('changePasswordBtn');
    const passwordModal = new bootstrap.Modal(document.getElementById('passwordModal'));
    const savePasswordBtn = document.getElementById('savePasswordBtn');
    const passwordForm = document.getElementById('passwordForm');

    // 加载个人信息
    function loadProfileInfo() {
        const teacherId = sessionStorage.getItem('teacherId');
        if (!teacherId) {
            console.error('未找到教师ID');
            return;
        }

        fetch(`http://localhost:8080/teacher/${teacherId}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    const teacher = data.data;
                    document.getElementById('profileUsername').textContent = teacher.username || '';
                    document.getElementById('profileEmail').textContent = teacher.email || '';
                    // 如果后端返回的数据中有createTime字段，则显示
                    if (teacher.createTime) {
                        document.getElementById('profileRegisterTime').textContent = teacher.createTime;
                    } else {
                        // 如果没有createTime字段，隐藏这一行
                        document.getElementById('profileRegisterTime').parentElement.style.display = 'none';
                    }
                } else {
                    throw new Error(data.message || '获取个人信息失败');
                }
            })
            .catch(error => {
                console.error('获取个人信息错误:', error);
                alert('获取个人信息失败：' + error.message);
            });
    }

    // 修改密码按钮点击事件
    changePasswordBtn.addEventListener('click', function() {
        alert('修改密码功能正在开发中，请稍后再试！');
        // passwordForm.reset();
        // passwordModal.show();
    });

    // 保存密码按钮点击事件（暂时注释，等待后端接口）
    savePasswordBtn.addEventListener('click', function() {
        const oldPassword = document.getElementById('oldPassword').value;
        const newPassword = document.getElementById('newPassword').value;
        const confirmNewPassword = document.getElementById('confirmNewPassword').value;

        if (!oldPassword || !newPassword || !confirmNewPassword) {
            alert('请填写所有密码字段！');
            return;
        }

        if (newPassword !== confirmNewPassword) {
            alert('两次输入的新密码不一致！');
            return;
        }

        // 暂时显示开发中的提示
        alert('修改密码功能正在开发中，请稍后再试！');
        passwordModal.hide();

        /* 等待后端接口完成后再启用
        const teacherId = sessionStorage.getItem('teacherId');
        const passwordData = {
            teacherId: parseInt(teacherId),
            oldPassword: oldPassword,
            newPassword: newPassword
        };

        fetch('http://localhost:8080/teacher/updatePassword', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(passwordData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('密码修改成功！');
                passwordModal.hide();
            } else {
                throw new Error(data.message || '密码修改失败');
            }
        })
        .catch(error => {
            console.error('密码修改错误:', error);
            alert('密码修改失败：' + error.message);
        });
        */
    });

    // 初始化页面时加载个人信息
    loadProfileInfo();

    // 初始化页面
    loadCourses();
}); 